const util = require('../../utils/util.js')
const app = getApp()
import {
  playBackground
} from '../../utils/audio.js'
Page({
  data: {
    log: '', // 屏幕实时输出
    tip: '请贴 NFC 卡片识别',
    src: ''          // 空的时候不展示 web-view
  },

  onLoad() {
    this.nfc = wx.getNFCAdapter()
    
  },

  onReady() {
    this.start() // 页面打开自动开始监听
  },
  onMessage(e) {
    const data = e.detail.data[0] // 数组，取第 1 条
    console.log(data)
    if (data && data.audioUrl) {
      // 交给后台音频管理器播放（锁屏继续）
      playBackground(data.audioUrl)
    }
  },

  onUnload() {
    this.stop()
  },

  start() {
    this.nfc.startDiscovery({
      success: () => {
        this.print('NFC 监听已开启，请贴卡...')
        this.nfc.onDiscovered(this.onDiscovered.bind(this))
      },
      fail: e => this.print('启动失败：' + e.errMsg)
    })
  },

  stop() {
    this.nfc.stopDiscovery()
    this.nfc.offDiscovered()
    this.print('已停止监听')
  },

  onDiscovered(res) {
    this.print('---- 检测到卡片 ----')
    this.print('技术数组：' + JSON.stringify(res.techs))

    // 1. 通用 UID（所有卡都有）
    const uid = util.buf2hex(res.id)
    this.print('UID：' + uid.toUpperCase())


    wx.request({
      url: "http://192.168.10.3:8085/nfc/page/" + uid.toUpperCase(),
      method:'GET',
      success:res => {
        console.log(res)
        res = JSON.stringify(res)
        res = JSON.parse(res)
      
        let id = res.data.data.id;
        console.log(res.data)
        this.setData({
          src:"http://192.168.10.3:8085/preview/"+id
        })
      }
    })

    // // 2. 按优先级挑一个最底层技术对象
    // const tech = this.pickTech(res.techs)
    // if (!tech) {
    //   this.print('未找到可用技术对象')
    //   return
    // }
    // this.print('选用技术：' + tech.tech)

    // // 3. 连接并读取原始信息
    // this.connectAndProbe(tech)
  },

  pickTech(techs) {
    // 优先级：IsoDep > NfcA > NfcB > NfcF > NfcV
    if (techs.includes('ISO_DEP')) return {
      tech: 'ISO_DEP',
      fn: () => this.nfc.getIsoDep()
    }
    if (techs.includes('NFC_A')) return {
      tech: 'NFC_A',
      fn: () => this.nfc.getNfcA()
    }
    if (techs.includes('NFC_B')) return {
      tech: 'NFC_B',
      fn: () => this.nfc.getNfcB()
    }
    if (techs.includes('NFC_F')) return {
      tech: 'NFC_F',
      fn: () => this.nfc.getNfcF()
    }
    if (techs.includes('NFC_V')) return {
      tech: 'NFC_V',
      fn: () => this.nfc.getNfcV()
    }
    return null
  },

  connectAndProbe({
    tech,
    fn
  }) {
    const tag = fn()
    tag.connect({
      success: () => {
        this.print('连接成功，开始探测...')
        // 根据技术发最通用的探测命令
        switch (tech) {
          case 'ISO_DEP':
            this.probeIsoDep(tag);
            break
          case 'NFC_A':
            this.probeNfcA(tag);
            break
          case 'NFC_B':
            this.probeNfcB(tag);
            break
          case 'NFC_F':
            this.probeNfcF(tag);
            break
          case 'NFC_V':
            this.probeNfcV(tag);
            break
        }
      },
      fail: e => this.print('连接失败：' + e.errMsg),
      complete: () => tag.close()
    })
  },

  /* ---------- 各技术最原始探测 ---------- */
  probeIsoDep(tag) {
    // 发送 RATS（ISO14443-4 请求）
    const rats = new Uint8Array([0xE0, 0x50]) // 默认 FSD=64，CID=0
    tag.transceive({
      data: rats.buffer,
      success: res => this.print('RATS 响应：' + util.buf2hex(res.data).toUpperCase()),
      fail: () => this.print('RATS 无响应')
    })
  },

  probeNfcA(tag) {
    // 读 UID 完整 7 字节 & SAK
    tag.getAtqa({
      success: ({
        atqa
      }) => this.print('ATQA：' + util.buf2hex(atqa).toUpperCase())
    })
    tag.getSak({
      success: ({
        sak
      }) => this.print('SAK：' + util.buf2hex(sak).toUpperCase())
    })
    tag.getUid({
      success: ({
        uid
      }) => this.print('完整 UID：' + util.buf2hex(uid).toUpperCase())
    })
  },

  probeNfcB(tag) {
    // ISO14443-B 的 Protocol_Info
    tag.getProtocolInfo({
      success: res => this.print('ProtocolInfo：' + util.buf2hex(res.data).toUpperCase()),
      fail: () => this.print('ProtocolInfo 无响应')
    })
  },

  probeNfcF(tag) {
    // FeliCa 系统代码请求
    const poll = new Uint8Array([
      0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
      0x01, 0x00, 0x06, 0x00, 0xFF, 0xFF,
      0x01, 0x81, 0x00, 0x00, 0x00
    ])
    tag.transceive({
      data: poll.buffer,
      success: res => this.print('FeliCa Poll 响应：' + util.buf2hex(res.data).toUpperCase()),
      fail: () => this.print('FeliCa Poll 无响应')
    })
  },

  probeNfcV(tag) {
    // ISO15693 Inventory
    const inv = new Uint8Array([0x01, 0x00]) // Flags=0x01, Command=Inventory
    tag.transceive({
      data: inv.buffer,
      success: res => this.print('15693 Inventory：' + util.buf2hex(res.data).toUpperCase()),
      fail: () => this.print('15693 Inventory 无响应')
    })
  },

  /* ---------- 日志输出 ---------- */
  print(msg) {
    const line = `[${new Date().toLocaleTimeString()}] ${msg}\n`
    console.log(line)
    this.setData({
      log: this.data.log + line
    })
    wx.pageScrollTo({
      scrollTop: 9999999
    }) // 自动滚到底
  }
})